﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WGCSFramework;
using System.IO;

namespace WebGrab
{
    public partial class mainWebGrab : Form
    {
        private int logCount = 0;
        private Timer timer = new Timer();
        private int imageId;

        public mainWebGrab()
        {
            InitializeComponent();
        }

        private void mainWebGrab_Load(object sender, EventArgs e)
        {
            this.addLogRow("Application start");
            this.infoSystemMessage.Text = "";
            this.controlUrlButtons(this.urlAdd, new EventArgs());
            this.restoreConfiguration();
        }

        private void restoreConfiguration()
        {
            //string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments).ToString() + "\\WebGrab\\";
            string path = "C:\\Documents and Settings\\Ondrej\\My Documents\\WebGrab\\";
            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
            this.fileOutPath.Text = path;
            int selected = 0;
            for (int i = 0; i < WGCSFramework.images.WgImages.getCodecNames().Length; i++)
            {
                this.setOutputFormat.Items.Add(WGCSFramework.images.WgImages.getCodecExtensions()[i]);
                if (WGCSFramework.images.WgImages.getCodecNames()[i] == "image/jpeg") selected = i;
            }
            this.setOutputFormat.SelectedIndex = selected;
            this.urlList.Items.Add("http://www.fuerte.cz");
            this.urlList.Items.Add("http://www.fmdesign.cz");
            this.urlList.Items.Add("http://www.google.cz");
            this.urlList.Items.Add("http://www.chc.cz");
            this.urlList.Items.Add("http://www.freshfake.com");
        }

        private void showSystemMessage(string text)
        {
            this.timer = new Timer();
            this.infoSystemMessage.Text = text;
            this.timer.Interval = 3600;
            this.timer.Tick += new EventHandler(hideSystemMessage);
            this.timer.Start();
        }

        public void hideSystemMessage(object source, EventArgs e)
        {
            this.infoSystemMessage.Text = "";
            this.timer.Stop();
        }

        private void buttAppTerminate_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void addLogRow(string text)
        {
            string nl = (this.logCount == 0) ? "" : Environment.NewLine;
            this.logCount++;
            this.infoLogScreen.Text = this.logCount.ToString() + ") " + text + nl + this.infoLogScreen.Text;
        }

        private void copyFieldToClipboard(object sender, EventArgs e)
        {
            TextBox t = sender as TextBox;
            Clipboard.SetDataObject(t.Text, true);
            t.SelectAll();
        }

        private void buttStart_Click(object sender, EventArgs e)
        {
            this.imageId = 1;
            this.doGrab();
        }

        private void doGrab()
        {
            this.urlList.SelectedIndex = (this.imageId - 1);
            string url = this.urlList.SelectedItem.ToString();
            //MessageBox.Show(url);
            WGCSFramework.images.WgBrowserGrab wp = new WGCSFramework.images.WgBrowserGrab();
            wp.isReady += new WGCSFramework.images.EventReady(handleGrabbedImage);
            wp.grabUrl(url);
        }

        private void handleGrabbedImage(object sender, EventArgs e)
        {
            WGCSFramework.images.WgBrowserGrab wp = sender as WGCSFramework.images.WgBrowserGrab;
            if (wp.message != "") MessageBox.Show(wp.message);
            this.addLogRow("Image captured: " + wp.getUrl);
            this.infoLastImage.Image = WGCSFramework.images.WgResizer.ResizeBitmap(wp.image, 246, 191);
            if (this.setSaveFile.Checked)
            {
                WGCSFramework.images.WgFileIoImage.saveJpeg(wp.image, Int16.Parse(this.setWidth.Text), Int16.Parse(this.setHeight.Text), this.fileOutPath.Text, this.getFileName(wp.getUrl), Int16.Parse(this.setQuality.Text));
            }
            this.imageId++;
            if (this.imageId <= this.urlList.Items.Count) this.doGrab();
        }

        private string getFileName(string url)
        {
            string id = this.imageId.ToString();
            string su = WGCSFramework.validations.strings.WgSafeText.getSafeUrl(url);
            string dt = WGCSFramework.validations.strings.WgSafeText.getSafeUrl(DateTime.Now.ToString());
            string newFileName = this.setFileName.Text;
            newFileName = System.Text.RegularExpressions.Regex.Replace(newFileName, @"\{ID\}", id);
            newFileName = System.Text.RegularExpressions.Regex.Replace(newFileName, @"\{DATETIME\}", dt);
            newFileName = System.Text.RegularExpressions.Regex.Replace(newFileName, @"\{URL\}", su);
            return newFileName;
        }

        private void validateNumberField(object sender, EventArgs e)
        {
            TextBox t = sender as TextBox;
            string orig = t.Text;
            WGCSFramework.validations.numbers.WgNumbers v = new WGCSFramework.validations.numbers.WgNumbers();
            WGCSFramework.validations.numbers.WgPorts p = new WGCSFramework.validations.numbers.WgPorts();
            if (t.Name == "setWidth")
            {
                t.Text = v.validateNumberInString(t.Text, 0, 1600, 800).ToString();
                if (t.Text != orig) this.showSystemMessage("Maximum width is 1600 px.");
            }
            else if (t.Name == "setHeight")
            {
                t.Text = v.validateNumberInString(t.Text, 0, 1200, 600).ToString();
                if (t.Text != orig) this.showSystemMessage("Maximum height is 1200 px.");
            }
            else if (t.Name == "setQuality")
            {
                t.Text = v.validateNumberInString(t.Text, 10, 100, 80).ToString();
                if (t.Text != orig) this.showSystemMessage("Picture quality must me between 10% and 100%");
            }
            else if (t.Name == "ftpPort")
            {
                t.Text = p.validatePortNumber(t.Text, 21).ToString();
                if (t.Text != orig) this.showSystemMessage("This is not a valid FTP port (default is 21)");
            }
        }

        private void showPass(object sender, EventArgs e)
        {
            CheckBox ch = sender as CheckBox;
            if (ch.Checked) this.ftpPass.UseSystemPasswordChar = false;
            else this.ftpPass.UseSystemPasswordChar = true;

        }

        private void controlUrlButtons(object sender, EventArgs e)
        {
            TextBox t = sender as TextBox;
            System.Text.RegularExpressions.Regex RgxUrl = new System.Text.RegularExpressions.Regex("(([a-zA-Z][0-9a-zA-Z+\\-\\.]*:)?/{0,2}[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?(#[0-9a-zA-Z;/?:@&=+$\\.\\-_!~*'()%]+)?");
            bool isUrl = false;
            if (RgxUrl.IsMatch(t.Text)) isUrl = true;
            else this.showSystemMessage("URL is invalid!");
            if (t.Text == "" || t.Text == "http://" || !isUrl)
            {
                this.buttUrlAdd.Enabled = false;
                this.buttUrlLoadList.Enabled = false;
            }
            else
            {
                this.buttUrlAdd.Enabled = true;
                this.buttUrlLoadList.Enabled = false;
            }

        }

        private void buttFileChangePath_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog browse = new System.Windows.Forms.FolderBrowserDialog();
            browse.ShowNewFolderButton = false;
            browse.Description = "Please select a folder";
            browse.RootFolder = System.Environment.SpecialFolder.DesktopDirectory;
            browse.SelectedPath = this.fileOutPath.Text;
            if (browse.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = browse.SelectedPath;
                string bs = "";
                if (path.Length > 3) bs = "\\"; 
                this.fileOutPath.Text = browse.SelectedPath + bs;
            }
        }

        private void buttFileFolderOpen_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(this.fileOutPath.Text);
        }

        private void buttUrlAdd_Click(object sender, EventArgs e)
        {
            this.urlList.Items.Add(this.urlAdd.Text);
        }

        private void buttUrlLoadList_Click(object sender, EventArgs e)
        {

        }

    }
}
